<template>
  <a-drawer :visible="visible" :title="title" @close="closeDrawer" destroy-on-close>
    <div>
      <a-form layout="vertical">
        <a-form-item label="规则名称" v-bind="validateInfos.name">
          <a-input placeholder="请输入规则名称"
                   v-model:value="modelRef.name"/>
        </a-form-item>
        <a-form-item label="所属公司" v-bind="validateInfos.org_branch_id">
          <a-select placeholder="请选择所属公司" v-model:value="modelRef.org_branch_id"
                    :options="companyList"/>
        </a-form-item>
        <a-form-item v-bind="validateInfos.rule">
          <template #label>
            <span>一键匹配规则</span>
            <a-tooltip>
              <template #title>
                <p>
                  优先费用类型排序，即先按照费用类型排序，相同费用类型按照应收/付日期从小到大排序；
                </p>
                <p>
                  优先应收/付日期排序，即先按照应收/付日期排序，相同日期按照费用类型排序。费用类型排序支持自定义，应收/付日期按照从小到大排序
                </p>
              </template>
              <question-circle-outlined class="ml-5"/>
            </a-tooltip>
          </template>
          <a-select placeholder="请选择匹配规则" :options="matchOptions"
                    v-model:value="modelRef.rule"/>
        </a-form-item>
        <a-form-item label="费用类型排序" v-bind="validateInfos.cost_types">
          <a-popover placement="right" title="添加费用类型"
                     trigger="click" v-model:visible="showCostType">
            <template #content>
              <a-cascader
                  v-model:value="temCostType"
                  :options="costTypeList"
                  :load-data="getCostTypeSub"
                  placeholder="请选择费用类型"
                  dropdownClassName="fee-type-cascader-custom"
                  @change="onCostTypeChange"
              />
            </template>
            <a-button type="primary" ghost @click="showCostType=true">+费用类型</a-button>
          </a-popover>

          <draggable
              class="list-group mr-10 mt-5"
              :list="modelRef.cost_types"
              group="collect"
              handle=".order-icon"
              draggable=".drag-item"
              itemKey="name">
            <template #item="{ element, index }">
              <div class="drag-item">
                <div class="flex flex-1 justify-start align-center show-drag ">
                  <unordered-list-outlined class=" order-icon"/>
                  <a-tag>{{ element.name }}</a-tag>
                </div>
                <close-outlined class="close" style="cursor: pointer"
                                @click="deleteTypeItem(index)"/>
              </div>
            </template>
          </draggable>
        </a-form-item>
      </a-form>

      <div class="drawer-footer">
        <a-button class="mr-10" @click="closeDrawer">取消</a-button>
        <a-button type="primary" @click="handleSave">保存</a-button>
      </div>
    </div>
  </a-drawer>
</template>

<script>
import {watch, ref, reactive, toRefs} from "vue";
import {Form, message} from "ant-design-vue";
import {
  QuestionCircleOutlined,
  UnorderedListOutlined,
  CloseOutlined,
  MenuOutlined
} from '@ant-design/icons-vue'
import draggable from 'vuedraggable'
import request from '@/common/utils/request'

const useForm = Form.useForm;
export default {
  components: {
    MenuOutlined,
    draggable,
    QuestionCircleOutlined,
    UnorderedListOutlined,
    CloseOutlined
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: undefined
    }
  },
  setup(props, context) {

    const state = reactive({
      title: "",
      companyList: [],
      showCostType: false,
      temCostType: undefined,
      startMove: false,
    })

    const closeDrawer = () => {
      context.emit("toClose")
    }
    const handleSave = () => {
      validate().then(() => {
        const params = {
          ...modelRef,
        }
        if (props.detail) {
          params.id = props.detail.id;
          request.put("/org", "/stream/match/rules", params).then(res => {
            message.success("操作成功！");
            context.emit("success");
            resetFields();
          })
        } else {
          request.post("/org", "/stream/match/rules", params).then(res => {
            message.success("操作成功！");
            context.emit("success");
            resetFields();
          })
        }
      })
    }

    const matchOptions = [{label: "优先费用类型排序", value: 1}, {
      label: "优先应收/应付日期排序",
      value: 2
    }]

    const modelRef = reactive({
      name: "",
      org_branch_id: undefined,
      rule: undefined,
      cost_types: [],


    })

    const ruleRef = reactive({
      name: [{
        required: true,
        message: "请输入规则名称"
      }],
      org_branch_id: [{
        required: true,
        message: "请选择所属公司"
      }],
      rule: [{
        required: true,
        message: "请选择匹配规则"
      }],
      cost_types: [{
        required: true,
        message: "请选择费用类型"
      }],
    })
    const {validate, resetFields, validateInfos} = useForm(modelRef, ruleRef)

    const costTypeList = ref([])
    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          costTypeList.value = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };


    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              costTypeList.value = [...costTypeList.value];
            }
          });
    };

    const getCompanyList = () => {
      request.get("/org", "/company/orgAndBranch").then(res => {
        console.log(res)
        state.companyList = res.list.map(item => {
          return {
            label: item.company,
            value: item.id,
          }
        })
      })
    }

    const setModelValue = () => {
      if (props.detail) {
        console.log(props.detail)
        modelRef.name = props.detail.name;
        modelRef.rule = props.detail.rule;
        modelRef.org_branch_id = props.detail.org_branch_id;
        modelRef.cost_types = props.detail.cost_types;
      }
    }

    const init = () => {
      getCostTypeList();
      getCompanyList();
      setModelValue();
    }

    watch(() => props.visible, (value) => {
      if (value) {
        state.title = !props.detail ? "新建匹配规则" : "编辑匹配规则";
        init();
      } else {
        resetFields();
      }
    })


    const onCostTypeChange = (e) => {
      if (e) {
        const index = e[0]
        const selItem = costTypeList.value.filter(item => {
          return item.value == index
        })
        const subItem = selItem[0].children.filter(item => {
          return item.value == e[1]
        })
        modelRef.cost_types.push({
          name: subItem[0].label,
          cost_type: subItem[0].value
        })
        setTimeout(() => {
          state.temCostType = undefined;
        }, 1000)
      }
      state.showCostType = false;
    }

    const deleteTypeItem = (index) => {
      modelRef.cost_types.splice(index, 1)
    }

    return {
      closeDrawer,
      handleSave,
      ...toRefs(state),
      validateInfos,
      modelRef,
      matchOptions,
      deleteTypeItem,
      getCostTypeList,
      getCostTypeSub,
      costTypeList,
      onCostTypeChange,


    }
  }
}
</script>

<style lang="less" scoped>

.drag-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #eeeeee;

  .order-icon {
    cursor: all-scroll;
    padding-right: 15px;
  }
}

</style>